<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row :gutter="25">
              <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入用户名" v-model="queryParams.name" /> 
              </el-col>
              <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入电话" v-model="queryParams.phone" /> 
              </el-col>
              <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入邮箱" v-model="queryParams.email" /> 
              </el-col>
              <el-col :span="4">
                  <el-input size="small" clearable placeholder="输入身份证" v-model="queryParams.identifyId" /> 
              </el-col>
              <el-col :span="4">
                  <el-select v-model="queryParams.state" filterable clearable placeholder="状态" size="small">
                    <el-option
                    v-for="item in statusList"
                    :key="item.id"
                    :label="item.keyDesc"
                    :value="item.value">
                    </el-option>
                </el-select>
              </el-col>
              <el-col :span="4" >
                  <el-button size="small" type="success" @click="queryPage" icon="el-icon-search" v-if="permissionStrValue.indexOf('userList:query') !== -1">查询</el-button>
              </el-col>
          </el-row>

            <!--放表格-->
        <el-table :data="list" border >
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="用户名">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.memberBo.username}}</span>
                </template>
            </el-table-column>
            <el-table-column label="邮箱" width="160px">
                <template slot-scope="scope">
                   <span style="color:#67C23A" size="medium">{{ scope.row.memberBo.email}}</span>
                </template>
            </el-table-column>
            <el-table-column label="身份证" width="160px">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.memberBo.identityId }}</span>
                </template>
            </el-table-column>
            <el-table-column label="联系电话">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.memberBo.phone }}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态">
                <template slot-scope="scope">
                    <el-tag type="success" size="mini" v-if="scope.row.memberBo.state == 0">正常</el-tag>
                    <el-tag type="danger" size="mini" v-if="scope.row.memberBo.state == 1">停用</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="角色">
                <template slot-scope="scope">
                    <el-tag v-for="item in scope.row.roles" :key="item.code" type="warning" effect="plain" size="mini">
                        {{item.name}}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="注册时间" width="160x">
                <template slot-scope="scope">
                    <span style="color:#67C23A" size="medium">{{ scope.row.memberBo.createTime}}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作" width="250px">
                 <template slot-scope="scope">
                     <el-button type="danger" size="small" @click="updateById(scope.row.memberBo.id, 1)" icon="el-icon-edit" v-if="scope.row.memberBo.state == 0 && permissionStrValue.indexOf('userList:update') !== -1">停用</el-button>
                     <el-button type="success" size="small" @click="updateById(scope.row.memberBo.id, 0)" icon="el-icon-edit" v-if="scope.row.memberBo.state == 1 && permissionStrValue.indexOf('userList:update') !== -1">启用</el-button>
                     <el-button type="primary" size="small" @click="showGiveToRoles(scope.row.memberBo.id)" icon="el-icon-check" v-if="permissionStrValue.indexOf('userList:giveRole') !== -1">分配角色 </el-button>
                 </template>
            </el-table-column>
        </el-table>

        <!--分页-->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.currPage"
          :page-sizes="[10,20, 30, 40, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog
       title="分配角色"
       :visible.sync="showToRole"
       width="40%">
       <el-form :model="userRoles" label-width="100px"  label-position="left" :rules="roleRules">
         <el-form-item label="已分配的角色:">
          <el-row :gutter="25">
              <el-col v-for="item in userRoles.assignRoles" :key="item.id" :span="6">
                  <el-checkbox :label="item.name" disabled v-model="checked"></el-checkbox>
              </el-col>
          </el-row>
         </el-form-item>
         <el-form-item label="所有角色:" >
          <el-row :gutter="25">
                <el-checkbox-group v-model="checkList" @change="handleChecck">
                    <el-col :span="6" v-for="item in userRoles.allRoles" :key="item.id">
                       <el-checkbox  :label="item.id">
                            {{item.name}}
                        </el-checkbox>
                      </el-col>
                </el-checkbox-group>
          </el-row>
         </el-form-item>
       </el-form>
       <span slot="footer" class="dialog-footer">
          <el-button @click="addFlag = false">取 消</el-button>
          <el-button type="primary" @click="giveUserToRoles()">确 定</el-button>
       </span>
     </el-dialog>


        </el-card>

    </div>
    

</template>

<script>
export default {
    name: "UserList",
    data() {
        return {
            queryParams: {
                id: '',
                name: '',
                phone: '',
                currPage: 1,
                pageSize: 10,
                identifyId: '',
                email: '',
                state: '',
                landlord: ''
            },
            list: [],
            total: 0,
            statusList: [
                {
                    id: 1,
                    keyDesc: '正常',
                    value: 0
                },
                {
                    id: 2,
                    keyDesc: '停用',
                    value: 1
                },
            ],
            showToRole: false,
            giveToRolesParam: {
                memberId: '',
                roleIds: []
            },
            userRoles: {
              assignRoles: [],
              allRoles: [],
            },
            roleRules: {

            },
            checked: true,
            checkList: [],
            userId: '',
            permissionStrValue: ''
            


        }
    },

    created() {
        this.queryPage()
        //获取权限值
       this.permissionStrValue = JSON.parse(window.sessionStorage.getItem('permissionList')).toString();

    },
    methods: {

         async queryPage() {
            const {data: res} = await this.$http.post('/user/member/list-page',JSON.stringify(this.queryParams), {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                }
            });
           console.log(res)
            if(res.success) {
                this.list = res.data;
                this.total = res.total;
            } else {
                this.$message.error(res.message);
            }
        },

        handleSizeChange(newPageSize) {
            this.queryParams.pageSize = newPageSize;
            this.queryPage();
        },
        handleCurrentChange(newPage) {
            this.queryParams.currPage = newPage;
            this.queryPage();

        },

        async updateById(id, state) {
            const confirmResult = await this.$confirm('是否更改该用户状态?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => {
                return err;
            });
            //当用户确认时，则返回值为字符串：confirm
            //取消时，返回字符串cancel
            if (confirmResult !== 'confirm'){
                return this.$message.info("已取消删除")
            }
            var param = new Object();
            param.id = id;
            param.state = state;
             //发送请求
            const{data: res} = await this.$http.post('/user/member/update-member-info', JSON.stringify(param), {
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                }
            });
            if(res.success) {
                this.$message.success("删除成功！");
                this.init();
                this.queryPage();
            } else {
                this.$message.error(res.message);
            }

        },
        init() {
             this.queryParams.name = '',
             this.queryParams.phone = '',
             this.queryParams.currPage = 1,
             this.queryParams.pageSize = 10,
             this.queryParams.identifyId = '',
             this.queryParams.email = '',
             this.queryParams.state = '',
             this.queryParams.landlord = ''

        },
        async giveUserToRoles() {
            if(this.checkList.length == 0) {
                return this.$message.error("分配的角色不能为空");
            }
            var param = new Object();
            param.memberId = this.userId;
            param.roleIds = this.checkList;
            const{data : res} = await this.$http.post('/user/role/give-member-to-roles', JSON.stringify(param), {
                 headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                }
            })
            if(res.success) {
                this.$message.success("分配成功！");
                this.checkList = [];
                this.queryPage();
                this.showToRole = false;
            } else {
                this.$message.error(res.message);
            }


        },
        async showGiveToRoles(id) {
           this.userId = id;
           const{data: res} = await this.$http.get(`/user/role/get-user-roles/${id}`);
           if(!res.success) {
              this.$message.error(res.message);
            }
            console.log(res.data.assignRoles)
            this.userRoles.assignRoles = res.data.assignRoles;
            this.userRoles.allRoles = res.data.allRoles;
            this.showToRole = true;

        },

        handleChecck(val) {
            console.log(val)
            this.checkList = val;
            
        }

    },
}
</script>